package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.TransferEventAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNAlbumResponse;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import easeui.utils.TextBase64Util;

public class TransferEventActivity extends Activity {
    private ListView cardsnyc_listview;
    private TextView cardsnyc_sure;
    public static ArrayList<YNAlbum> tagList = new ArrayList<YNAlbum>();
    private Gson gson;
    private BaseApplication application;
    private HttpConfig mHttpConfig;
    private TransferEventAdapter transferEventAdapter;
    private List<YNAlbum> YNAlbumlist = new ArrayList<>();
    private String groupIds;
    private int groupIdMy;
    private int eid;
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_transfevent);
        init();
        initView();
        getAlbumListById(application.getCurID());
    }

    private void init() {
        gson = new Gson();
        application = (BaseApplication) getApplication();
        mHttpConfig = new HttpConfig(TransferEventActivity.this);
        registerBroadcastReceiver();
        YNAlbumlist.clear();
        tagList.clear();
        eid = YNSingleton.getInstance().getCurStatus().getEid();
        groupIdMy = application.getCurGid();
        type = getIntent().getIntExtra("type", 0);
    }

    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.updataSyncUploadok);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.updataSyncUploadok:
                    cardsnyc_sure.setTextColor(getResources().getColor(R.color.user_color_green));
                    break;
            }
        }
    };

    private void initView() {
        cardsnyc_sure = (TextView) findViewById(R.id.cardsnyc_sure);
        cardsnyc_listview = (ListView) findViewById(R.id.cardsnyc_listview);
        cardsnyc_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tagList.size() == 0) {
                    Toast.makeText(TransferEventActivity.this, "请选择圈子", Toast.LENGTH_SHORT).show();
                    return;
                }
                StringBuilder builder = new StringBuilder();
                for (int j = 0; j < tagList.size(); j++) {
                    builder.append(tagList.get(j).getGroupid() + ",");
                }
                String taglistr = builder.toString();
                groupIds = taglistr.substring(0, taglistr.length() - 1);
                if (SystemUtils.isFastClick()) {
                    return;
                }
                transfEvent(groupIds);
            }
        });
        findViewById(R.id.transfer_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void getAlbumListById(int uId) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(uId));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowPhoto))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAlbumResponse resGroup = gson.fromJson(s, YNAlbumResponse.class);
                        if (resGroup != null && ReqUtils.isSuccess(resGroup.getCode())) {
                            // 通知列表更新
                            List<YNAlbum> list = resGroup.getData();
                            for (int i = 0; i < list.size(); i++) {
                                if (list.get(i).getGroupid() != groupIdMy) {
                                    YNAlbumlist.add(list.get(i));
                                }
                            }
                            if (YNAlbumlist.size() > 0) {
                                transferEventAdapter = new TransferEventAdapter(TransferEventActivity.this, YNAlbumlist);
                                cardsnyc_listview.setAdapter(transferEventAdapter);
                                transferEventAdapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(TransferEventActivity.this, "没有可同步的圈子", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(TransferEventActivity.this, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT)
                                .show();
                    }
                });
        LiteHttp.newApacheHttpClient(mHttpConfig).executeAsync(req);
    }


    private void transfEvent(String groupIds) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_EID, String.valueOf(eid));
        mParam.put(CommonConstants.YNS_GROUP_ID, groupIds);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynTransferEvent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s.toString());
                            if (jsonObject.optInt("code") == 0) {
                                YNStatusResponse resAlbumStatus = gson.fromJson(s, YNStatusResponse.class);
                                if (resAlbumStatus != null && ReqUtils.isSuccess(resAlbumStatus.getCode())) {
                                    List<YNStatus> statusLists = new ArrayList<>();
                                    statusLists.addAll(resAlbumStatus.getData());
//                                    for (int i = 0; i < statusLists.size(); i++) {
//                                        sendHuanXinMessage(tagList.get(i).getGimid(), type, statusLists.get(i));
//                                    }
                                }
                                Toast.makeText(TransferEventActivity.this, "同步成功", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(TransferEventActivity.this, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT)
                                .show();
                    }
                });
        LiteHttp.newApacheHttpClient(mHttpConfig).executeAsync(req);
    }

    private void sendHuanXinMessage(String gimid, int type, YNStatus ynStatus) {
        String title = null;
        switch (type) {
            case 0:
                title = "上传了照片";
                break;
            case 1:
                title = "发布了一张记录卡片";
                break;
            case 2:
                title = "发布了一张语音图集";
                break;
            case 3:
                title = "发布了一日一记";
                break;
        }
        EMMessage message = EMMessage.createTxtSendMessage(TextBase64Util.encode(title), gimid);
        if (message == null) {
            return;
        }
        message.setChatType(EMMessage.ChatType.GroupChat);
        YNUser ynUser = application.getCurUser();
        message.setAttribute("type", String.valueOf(type));
        message.setAttribute("accountName", ynUser.getUnickname());
        message.setAttribute("img", ynUser.getUpic());
        message.setAttribute("fristpic", ynStatus.getEfirstpic());
        message.setAttribute("eventId", ynStatus.getEid());
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mBroadcastReceiver);
    }


    // 友盟统计
    public void onResume() {
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        super.onResume();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
